package com.MyRunnableDemo.Test;

public class SellTicket implements Runnable {

    private static int tickets = 100;

    private Object obj = new Object();

    private int x = 0;

    @Override
    public void run() {
        while (true) {
            if (x % 2 == 0) {
//                synchronized (obj) {
//                synchronized (this) {
                synchronized (SellTicket.class) {
                    if (tickets > 0) {
                        //通过sleep（）方法模拟出票时间
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在售卖，剩余" + tickets + "张");
                        tickets--;
                    }
                }
            } else {
//                synchronized (obj) {
//                    if (tickets > 0) {
//                        //通过sleep（）方法模拟出票时间
//                        try {
//                            Thread.sleep(100);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        System.out.println(Thread.currentThread().getName() + "正在售卖，剩余" + tickets + "张");
//                        tickets--;
//                    }
//                }
                sellTicket();
            }
            x++;


        }

    }

    private static synchronized void sellTicket() {
        if (tickets > 0) {
            //通过sleep（）方法模拟出票时间
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在售卖，剩余" + tickets + "张");
            tickets--;
        }
    }
}
